<template>
  <ContentWrap>
    <!-- 搜索栏 -->
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="90px"
    >
      <el-form-item label="视频名称" prop="name">
        <el-input
          v-model="queryParams.name"
          class="!w-240px"
          clearable
          placeholder="请输入视频名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button
          v-hasPermi="['video:page:add']"
          plain
          type="primary"
          @click="openVideoUpload('create')"
        >
          <Icon class="mr-5px" icon="ep:upload" />
          视频上传
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 视频列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
      <el-table-column type="selection" label="id" align="center" key="id" prop="id" />
      <el-table-column label="ID" align="center" prop="id" :width="60" />
      <el-table-column prop="thumb" label="封面" align="center">
        <template #default="scope">
          <div class="image-video" @click="handleVideo(scope.row)">
            <el-icon>
              <VideoPlay />
            </el-icon>
            <el-image :src="scope.row.thumb" style="max-width: 100px; max-height: 100px">
              <template #error>
                <div class="image-slot">
                  <el-icon>
                    <icon-picture />
                  </el-icon>
                </div>
              </template>
            </el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="名称" align="center" />
      <el-table-column prop="source" label="来源" align="center" />
      <el-table-column prop="author" label="作者" align="center" />
      <el-table-column prop="duration" label="时长" align="center">
        <template #default="scope"> {{ scope.row.duration }}(秒) </template>
      </el-table-column>
      <el-table-column prop="ext" label="格式" align="center" />
      <el-table-column prop="status" label="状态" align="center">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.VIDEO_TRANSCODER_STATUS" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template #default="scope">
          <div class="flex items-center justify-center">
            <el-button type="primary" link @click="handleDetail(scope.row.id)">
              <Icon icon="ep:edit" />
              详情
            </el-button>
            <el-button type="primary" link @click="openVideoUpload('update', scope.row.id)">
              <Icon icon="ep:edit" />
              修改
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <update ref="updateRef" :type="1" />
  <SubmitAuditFrom ref="submitAuditRef" @success="getList"></SubmitAuditFrom>
  <videoDialog
    ref="videoDialogRef"
    :dialogTitle="dialogTitle"
    :currentSource_src="currentSource_src"
  />
</template>
<script lang="ts" setup>
import { ref, reactive } from 'vue'
import Update from '@/views/video/update.vue'
import * as videoApi from '@/api/video'
import 'video.js/dist/video-js.css'
import router from '@/router'
import { DICT_TYPE } from '@/utils/dict'
import videojs from 'video.js'
import {ElMessage} from "element-plus";
import SubmitAuditFrom from "@/views/resource/meta/SubmitAuditFrom.vue";

// import videoDialog from './videoDialog.vue'
const queryFormRef = ref<any>()
const dialogTitle = ref('视频播放')
const currentSource_src = ref('')
const videoDialogRef = ref()
const showImageUploadDialogFlag = ref(false)
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: null,
  type: 1,
  createTime: []
})
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据

const checked = ref([])

const handleVideo = (row) => {
  console.log(row)
  currentSource_src.value = row.url.replace('m3u8', 'mp4')
  videoDialogRef.value.open('打开dialog')
}

const updateRef = ref<any>()
const selectedItems = ref([])
const submitAuditRef = ref()
const handleSelectionChange = (row) => {
  selectedItems.value = row
}

const batchAuditing = async () => {
  if (selectedItems.value.length == 0 || selectedItems.value.length > 10) {
    ElMessage.warning('请选择要审核的数据!')
    return
  }
  let ids = []
  selectedItems.value.forEach((res) => {
    ids.push(res.id)
  })
  submitAuditRef.value.open(2,0,ids)
  // if (ids.length > 0) {
  //   await metaApi.auditing(id, ids)
  // }
  // await getList()
}

const openVideoUpload = (type: string, id?: number) => {
  updateRef.value.openDialog(type, id)
}
const message = useMessage()
const deleted = async (rid) => {
  try {
    await message.confirm('确定删除该条数据吗？')
    let ids = []
    ids.push(rid)
    await videoApi.deleted(ids)
    await getList()
  } catch {}
}
//资源回收站
const recycle = () => {
  router.push({
    path: '/resource/video/recycle'
  })
}
const closeDialog = () => {
  showImageUploadDialogFlag.value = false
}
const detail = (id) => {}
const getList = async () => {
  loading.value = true
  try {
    const data = await videoApi.page(queryParams)
    list.value = data.list
    total.value = data.total
    // info()
  } finally {
    loading.value = false
  }
}
const handleQuery = () => {
  getList()
}
const handleDetail = (id) => {
  router.push({
    path: 'detail',
    query: {
      id: id,
      buttonState: true
    }
  })
}

const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

provide('getList', getList)
const clientWidth = ref(0)
const clientHeight = ref(0)
/** 初始化 **/
onMounted(() => {
  getList()
  clientWidth.value = '100px'
  clientHeight.value = '56px'
  // clientWidth.value = window.document.querySelector('.vdl-top')?.clientWidth
  // clientHeight.value = window.document.querySelector('.vdl-top')?.clientHeight
})
const videoForm = ref({})
const info = async () => {
  increment()
}
// DOM更新后执行videojs初始化函数
async function increment() {
  await nextTick()
  initVideoSource()
}
onUnmounted(() => {
  // list.value.map((item, index) => {
  //   var player = videojs('my-video' + item.id)
  //   player.dispose() // 销毁播放器实例
  // })
})

// 创建一个自定义Tech
class CustomTech extends videojs.getTech('Html5') {
  // 重写play方法以拦截播放请求
  play() {
    // 在播放请求发送之前，可以添加自己的逻辑
    console.log(this.currentSource_)
    currentSource_src.value = this.currentSource_.src
    console.log('播放请求被拦截')
    videoDialogRef.value.open('打开dialog')
    // 确保调用原有逻辑，否则视频不会播放
    return super.play()
  }

  // 自定义方法来获取DOM
  getDomElement() {
    console.log(this)
    // 返回播放器的DOM元素
    // return this.el_;
  }
}
// 注册自定义Tech
videojs.registerTech('Custom', CustomTech)
// 定义 videojs 实例
const myPlayer = ref()

const videoIdList = reactive(['-top'])
// videojs 初始化函数
function initVideoSource() {
  console.log(list.value)
  list.value.map((item, index) => {
    console.log('item', item)
    myPlayer.value = videojs('my-video' + item.id, {
      width: '126px', //播放器高度
      height: '80px', //播放器高度
      // width: clientWidth.value, //播放器高度
      // height: clientHeight.value, //播放器高度
      controls: true, // 是否显示控制条
      preload: 'auto',
      autoplay: false, // 自动播放
      loop: false, // 循环播放
      // fluid: true, // 自适应宽高
      language: 'zh-CN', // 设置语言
      muted: true, // 是否静音
      inactivityTimeout: false,
      // 设置控制条组件
      controlBar: {
        // 设置控制条组件
        //  设置控制条里面组件的相关属性及显示与否
        currentTimeDisplay: true,
        timeDivider: true,
        durationDisplay: true,
        remainingTimeDisplay: false,
        volumePanel: {
          inline: false
        },
        pictureInPictureToggle: false
      },
      userActions: {
        seek: false
      },
      techOrder: ['custom', 'html5']
    })
  })
}
</script>
<style lang="scss" scoped>
.image-video {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;

  .el-icon {
    z-index: 999;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 35px;
    color: #ffffff;
  }
}

::v-deep(.vjs-big-play-button) {
  // width: 50px;
  // height: 28px;
  top: calc((80px - 1.63332em) / 2);
  left: calc((150px - 3em - 12px - 12px) / 2);
}

.block-left {
  display: inline-block;
  width: 70%;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.block-right {
  display: inline-block;
  width: 30%;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.dialog-footer {
  text-align: center;
}

.body {
  margin: 0;
}

.demo-image__error {
  .de-checkbox {
    .de-vide {
      height: 330px;
    }
  }
}

.demo-image__error .block {
  display: inline-block;
  width: 20%;
  padding: 30px 20px;
  text-align: center;
  vertical-align: top;
  border-right: solid 1px var(--el-border-color);
  box-sizing: border-box;
}

.demo-image__error .block .more {
  float: right;
  color: #8c8a8a;
}

.demo-image__error .demonstration {
  display: block;
  display: inline-block;
  margin-top: 10px;
  margin-bottom: 20px;
  font-size: 14px;
  color: var(--el-text-color-secondary);
  text-align: left;
}

.demo-image__error .datetime {
  display: block;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
  text-align: left;
}

.demo-image__error .checkbox {
  display: block;
  margin-bottom: 10px;
  font-size: 14px;
  text-align: left;
}

.demo-image__error .image-slot {
  display: flex;
  width: 100%;
  height: 100%;
  font-size: 30px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-light);
  justify-content: center;
  align-items: center;
}

.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}

.option {
  display: flex;
  float: right;
  color: #8c8e91;
  cursor: pointer;
  align-items: center;
}

.videoBox {
  width: 100%;
  height: 100%;
  max-width: 300px;
  max-height: 300px;
}
</style>
